package com.wanli.agent.homepage;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ethanhua.skeleton.Skeleton;
import com.ethanhua.skeleton.SkeletonScreen;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.wanli.agent.R;
import com.wanli.agent.base.BaseActivity;
import com.wanli.agent.base.DataCallBack;
import com.wanli.agent.bean.BusinessProviderOrMerchantInfoBean;
import com.wanli.agent.bean.UserInfoBean;
import com.wanli.agent.homepage.adapter.ProviderOrMerchantDataListAdapter;
import com.wanli.agent.homepage.model.HomePageModelImpl;
import com.wanli.agent.homepage.model.IHomePageModel;
import com.wanli.agent.utils.LogUtils;
import com.wanli.agent.utils.SPManager;
import com.wanli.agent.widget.AppTitleBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 经营数据
 * 1、roleFlag的条件下，header业绩数据对应展示
 * 2、roleFlag的条件下，列表第二个表头对应更改
 */
public class BusinessDataDetailActivity extends BaseActivity implements OnRefreshLoadMoreListener {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.tvName)
    TextView tvName;
    @BindView(R.id.tvProductVersion)
    TextView tvProductVersion;
    @BindView(R.id.tvDealAmountTotal)
    TextView tvDealAmountTotal;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvValue)
    TextView tvValue;
    @BindView(R.id.etSearch)
    EditText etSearch;
    @BindView(R.id.view_cancel)
    View viewCancel;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.tvSearch)
    TextView tvSearch;
    @BindView(R.id.tvDealAmount)
    TextView tvDealAmount;
    @BindView(R.id.tvDealCount)
    TextView tvDealCount;
    @BindView(R.id.tvDate)
    TextView tvDate;
    @BindView(R.id.ll_no_data)
    LinearLayout llNoData;
    @BindView(R.id.rvData)
    RecyclerView rvData;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private SkeletonScreen skeletonScreen;
    private IHomePageModel homePageModel;
    private UserInfoBean userInfoBean;
    private List<BusinessProviderOrMerchantInfoBean.DataBean> beanList = new ArrayList<>();
    private ProviderOrMerchantDataListAdapter adapter;
    private String productVersion = "1";
    private int page = 1;
    private String dealAmount = "";
    private String merchantCountOrDealCount = "";
    private String keyword = "";
    private String startTime = "";
    private String endTime = "";
    private String month = "2022-07";
    private String yesterday = "";
    private String branchName = "";
    private String agentId = "";
    private String dealAmountSeq = "desc";
    private String merchantOrDealCountSeq = "";
    private int roleFlag = 0;// 0-直属服务商，1-直属商户

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_business_data_detail);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        Intent intent = getIntent();
        if (intent != null) {
            startTime = intent.getStringExtra("startTime");
            endTime = intent.getStringExtra("endTime");
            yesterday = intent.getStringExtra("yesterday");
            month = intent.getStringExtra("month");
            branchName = intent.getStringExtra("branchName");
            productVersion = intent.getStringExtra("productVersion");
            dealAmount = intent.getStringExtra("dealAmount");
            merchantCountOrDealCount = intent.getStringExtra("merchantCountOrDealCount");
            agentId = intent.getStringExtra("agentId");
            roleFlag = intent.getIntExtra("roleFlag", 0);
        }
        LogUtils.e("经营数据", new Gson().toJson(intent));
        homePageModel = new HomePageModelImpl();
        userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);

        if (roleFlag == 0) {
            etSearch.setHint("服务商名称");
            tvTitle.setText("新增商户数");
            tvDealCount.setText("新增商户数");
        } else {
            etSearch.setHint("商户名称");
            tvTitle.setText("交易笔数");
            tvDealCount.setText("交易笔数");
        }
        if (productVersion.equals("1")) {
            tvProductVersion.setText("标准版");
        } else if (productVersion.equals("2")) {
            tvProductVersion.setText("智能版");
        } else {
        }
        tvName.setText(branchName);
        tvDealAmountTotal.setText(dealAmount);
        tvValue.setText(merchantCountOrDealCount);
        if (!TextUtils.isEmpty(yesterday)) {
            tvDate.setText("时间范围：" + yesterday);
        } else if (!TextUtils.isEmpty(month)) {
            tvDate.setText("时间范围：" + month);
        } else if (!TextUtils.isEmpty(startTime) && !TextUtils.isEmpty(endTime)) {
            tvDate.setText("时间范围：" + startTime + " 至 " + endTime);
        }

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!TextUtils.isEmpty(keyword)) {
                        refreshData();
                    }
                    return true;
                }
                return false;
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                keyword = etSearch.getText().toString().trim();

                if (!TextUtils.isEmpty(keyword)) {
                    viewCancel.setVisibility(View.VISIBLE);
                } else {
                    viewCancel.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        refreshLayout.setRefreshHeader(new ClassicsHeader(mActivity));//设置Header
        refreshLayout.setRefreshFooter(new ClassicsFooter(mActivity));//设置Footer
        refreshLayout.setOnRefreshLoadMoreListener(this);

        adapter = new ProviderOrMerchantDataListAdapter(beanList, roleFlag);
        rvData.setLayoutManager(new LinearLayoutManager(mActivity));
        rvData.setAdapter(adapter);

        skeletonScreen = Skeleton.bind(rvData)
                .adapter(adapter)
                .color(R.color.shimmer_color_1)
                .shimmer(true)
                .angle(20)
                .frozen(false)
                .duration(1000)
                .count(20)
                .load(R.layout.item_skeleton_agent_list)
                .show();

        getProviderOrMerchantInfo();
    }

    public void refreshData() {
        page = 1;
        beanList.clear();
        getProviderOrMerchantInfo();
        adapter.notifyDataSetChanged();
        refreshLayout.finishRefresh(30000);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        getProviderOrMerchantInfo();
        refreshLayout.finishLoadMore(30000);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshData();
    }

    public void getProviderOrMerchantInfo() {
        homePageModel.getProviderOrMerchantInfo(productVersion, agentId, 20, page, keyword, keyword, yesterday, month, startTime, endTime, dealAmountSeq, merchantOrDealCountSeq, roleFlag, new DataCallBack<BusinessProviderOrMerchantInfoBean>() {
            @Override
            public void onSuccessful(BusinessProviderOrMerchantInfoBean bean) {
                LogUtils.e("经营数据resp","BusinessProviderOrMerchantInfoBean：" + new Gson().toJson(bean));
                if (bean.getData() != null && bean.getData().size() > 0) {
                    beanList.addAll(bean.getData());
                    if (page == 1) {
                        refreshLayout.finishRefresh();
                    } else {
                        refreshLayout.finishLoadMore();
                    }
                } else {
                    if (page != 1) {
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.finishRefresh();
                    }
                }
                if (beanList.size() > 0) {
                    llNoData.setVisibility(View.GONE);
                } else {
                    llNoData.setVisibility(View.VISIBLE);
                }
                adapter.notifyDataSetChanged();
                if (page == 1) {
                    skeletonScreen.hide();
                }
            }

            @Override
            public void onFailed(String msg, String code) {
                LogUtils.e("经营数据resp","code - msg：" + code + " - " + msg);
            }
        });
    }

    @OnClick({R.id.tvSearch, R.id.view_cancel, R.id.tvDealAmount, R.id.tvDealCount})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvSearch:
                refreshData();
                break;
            case R.id.view_cancel:
                keyword = "";
                etSearch.setText("");
                refreshData();
                break;
            case R.id.tvDealAmount:
                if (TextUtils.isEmpty(dealAmountSeq)) {
                    dealAmountSeq = "desc";
                    tvDealAmount.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(this, R.mipmap.ic_seq_asc), null);
                } else {
                    if (dealAmountSeq.equals("asc")) {
                        dealAmountSeq = "desc";
                        tvDealAmount.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(this, R.mipmap.ic_seq_asc), null);
                    } else {
                        dealAmountSeq = "asc";
                        tvDealAmount.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(this, R.mipmap.ic_seq_desc), null);
                    }
                }
                merchantOrDealCountSeq = "";
                tvDealCount.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(this, R.mipmap.ic_seq_default), null);
                LogUtils.e("经营数据","dealAmountSeq：" + dealAmountSeq);
                refreshData();
                break;
            case R.id.tvDealCount:
                if (TextUtils.isEmpty(merchantOrDealCountSeq)) {
                    merchantOrDealCountSeq = "desc";
                    tvDealCount.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(this, R.mipmap.ic_seq_asc), null);
                } else {
                    if (merchantOrDealCountSeq.equals("asc")) {
                        merchantOrDealCountSeq = "desc";
                        tvDealCount.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(this, R.mipmap.ic_seq_asc), null);
                    } else {
                        merchantOrDealCountSeq = "asc";
                        tvDealCount.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(this, R.mipmap.ic_seq_desc), null);
                    }
                }
                dealAmountSeq = "";
                tvDealAmount.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(this, R.mipmap.ic_seq_default), null);
                LogUtils.e("经营数据","merchantOrDealCountSeq：" + merchantOrDealCountSeq);
                refreshData();
                break;
        }
    }
}
